package com.hearwego;

import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.util.List;

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.HttpStatus;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.conn.scheme.Scheme;
import org.apache.http.conn.ssl.SSLSocketFactory;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.util.EncodingUtils;
import org.apache.http.util.EntityUtils;

import com.utilities.HWGSQLiteHelper;
import com.utilities.Informacion;
import com.utilities.RssParserPull;

import android.app.ProgressDialog;
import android.content.ContentValues;
import android.content.Context;
import android.content.SharedPreferences;
import android.database.Cursor;
import android.database.SQLException;
import android.database.sqlite.SQLiteDatabase;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.net.http.AndroidHttpClient;
import android.os.AsyncTask;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentTransaction;
import android.util.Log;
import android.util.Xml.Encoding;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.Toast;

public class TabFragment extends Fragment {

    private static final int LIST_STATE = 0x1;
    private static final int GRID_STATE = 0x2;
    private static final int DESCR_STATE = 0x3;
    private int mTabState, actualId;
    ProgressDialog dialog, dialog1;
	HWGSQLiteHelper usdbh;
	SQLiteDatabase db;
	List<Informacion> informacion;
	SharedPreferences preferences;
	SharedPreferences.Editor editor;
	Bitmap bm = null;
	String _response;

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.ac_fragment_tab, container, false);
		usdbh =new HWGSQLiteHelper(getActivity(), "DBHWG", null, 1);
        db = usdbh.getWritableDatabase();
    	db.rawQuery("DELETE FROM Detalle", null);
		
		preferences = getActivity().getSharedPreferences("Preferencias",Context.MODE_PRIVATE);
		editor = preferences.edit();
		actualId = preferences.getInt("actualid", 0);
		
		new getInfoHeader().execute("");
		
        Button listViewTab = (Button) view.findViewById(R.id.list_view_tab);
        Button gridViewTab = (Button) view.findViewById(R.id.grid_view_tab);
        Button descripcionTab = (Button) view.findViewById(R.id.descripcion);

        gotoListView();
        listViewTab.setOnClickListener(new OnClickListener() {
            public void onClick(View v) {
                gotoListView();
            }
        });
        gridViewTab.setOnClickListener(new OnClickListener() {
            public void onClick(View v) {
            gotoDetalleView();
            }
        });

        descripcionTab.setOnClickListener(new OnClickListener() {
            public void onClick(View v) {
                gotoDescriptionView();
            }
        });

        return view;
    }
    
    /********OBTENER EL ID DEL EVENTO DE LAS PREFERENCIAS CON EL NOMBRE "actualid"********/

	protected void gotoDescriptionView() {
	        if (mTabState != DESCR_STATE) {
	            mTabState = DESCR_STATE;
	            FragmentManager fm = getFragmentManager();
	            if (fm != null) {
	                FragmentTransaction ft = fm.beginTransaction();
	                ft.replace(R.id.fragment_content_header, new TabFragmentHeader());
	                ft.replace(R.id.fragment_content, new DescripcionFragment());
	                ft.commit();
	            }
	      }
	}
	
	public void gotoListView() {
	        if (mTabState != LIST_STATE) {
	            mTabState = LIST_STATE;
	            FragmentManager fm = getFragmentManager();
	            if (fm != null) {
	                FragmentTransaction ft = fm.beginTransaction();
	                ft.replace(R.id.fragment_content_header, new TabFragmentHeader());
	                ft.replace(R.id.fragment_content, new LocationListFragment());
	                ft.commit();
	            }
	        }
	    }

    public void gotoDetalleView() {
        if (mTabState != GRID_STATE) {
            mTabState = GRID_STATE;
            FragmentManager fm = getFragmentManager();
            if (fm != null) {
                FragmentTransaction ft = fm.beginTransaction();
                ft.replace(R.id.fragment_content_header, new TabFragmentHeaderDetalle());
                ft.replace(R.id.fragment_content, new DetalleFragment());
                ft.commit();
            }
        }
    }
    
	class getInfoHeader extends AsyncTask<String, String, String>{
		
		@Override
		protected void onPreExecute() {
			super.onPreExecute();
		}

		@Override
		protected String doInBackground(String... params) {
			Log.i("inicio", "inicio");
			RssParserPull parse = new RssParserPull("http://www.smartthinking.com.mx:8080/HearWeGo/DataServlet?Query=select%20*%20from%20pois%20where%20poi_idr="+actualId+"&BaseDatos=hwg");
			informacion = null;
			informacion = parse.parse();
			Log.i("fin", "fin" + parse);

	        if(db != null)
	        {
	          for(int i=0; i < informacion.size();i++){
	        	  
		          Log.i("url de descarga", "http://www.smartthinking.com.mx:8080/HearWeGo/"+informacion.get(i).getFoto());
	        	  DefaultHttpClient mHttpClnt = new DefaultHttpClient();
	  	          mHttpClnt.getConnectionManager().getSchemeRegistry().register(new Scheme("SSLSocketFactory", SSLSocketFactory.getSocketFactory(), 443));

	        	  HttpGet mHttget = new HttpGet("http://www.smartthinking.com.mx:8080/HearWeGo/"+informacion.get(i).getFoto().replace(" ", "%20"));
	        	  try {
					HttpResponse mHttpReps = mHttpClnt.execute(mHttget);
					if(mHttpReps.getStatusLine().getStatusCode() == HttpStatus.SC_OK){
						HttpEntity entity = mHttpReps.getEntity();
						if(entity != null){
							byte[] bb = EntityUtils.toByteArray(entity);
							bm = BitmapFactory.decodeByteArray(bb, 0, bb.length);
							int bmWidth = bm.getWidth();
							int bmHeight = bm.getHeight();
							bm = Bitmap.createBitmap(bm, (bmWidth-bmHeight)/2, 0, bmHeight, bmHeight);
	
							Bitmap scaledBm = Bitmap.createScaledBitmap(bm, 80, 80, true);
							ByteArrayOutputStream stream = new ByteArrayOutputStream();
							scaledBm.compress(Bitmap.CompressFormat.PNG, 50, stream);
							byte[] byteArray = stream.toByteArray();
							stream.flush();

				        	  try {
									db.execSQL("INSERT INTO Detalle (poi_idr, poi_nombre, poi_foto, poi_direccion, poi_metro, poi_metrobus, poi_servicios," +
												"poi_clasificacion, poi_www, poi_mail, poi_tel, poi_lat, poi_lng, poi_idioma, poi_ruta, poi_horario, " +
												"poi_costo, poi_descripcion, poi_cuentaporcentaje, poi_entradalibre, poi_encabezado,bitmapfoto) " +
									               "VALUES ('" +informacion.get(i).getId().toString()+"', '"+informacion.get(i).getNombre()+"', '"+informacion.get(i).getFoto()+"'," +
									               		"'"+informacion.get(i).getDireccion()+"', '"+informacion.get(i).getMetro()+"', '"+informacion.get(i).getMetroBus()+"'," +
									               		"'"+informacion.get(i).getServicios()+"', '"+informacion.get(i).getClacificacion()+"', '"+informacion.get(i).getWww()+"'," +
									               		"'"+informacion.get(i).getMail()+"','"+informacion.get(i).getTel()+"', '"+informacion.get(i).getLat()+"', '"+informacion.get(i).getLng()+"'," +
									               		"'"+informacion.get(i).getIdioma()+"', '"+informacion.get(i).getRuta()+"', '"+informacion.get(i).getHorario()+"'," +
									               		"'"+informacion.get(i).getCosto()+"', '"+informacion.get(i).getDescripcion()+"', '"+informacion.get(i).getCuenta_porcentaje()+"', '"+informacion.get(i).getEntradaLibre()+"'," +
									               		"'"+informacion.get(i).getEncabezado()+"', '"+byteArray+"')");
								} catch (SQLException e) {
									e.printStackTrace();
					          } 
						}
				}
				} catch (ClientProtocolException e) {
					e.printStackTrace();
				} catch (IOException e) {
					e.printStackTrace();
				}
	         }
	        }
			return null;
		}
		
		@Override
		protected void onPostExecute(String result) {
			super.onPostExecute(result);
            db.close();
    		new LoagGastos().execute("");
		}
	}
	
	public class LoagGastos extends AsyncTask<String, String, String>{
    	int zeroGastos = -1;
    	
    	@Override
    		protected void onPreExecute() {
    			super.onPreExecute();
    		}
    	
		@Override
		protected String doInBackground(String... params) {
			HWGSQLiteHelper usdbh =new HWGSQLiteHelper(getActivity(), "DBHWG", null, 1);
	        final SQLiteDatabase db = usdbh.getWritableDatabase();
	        if(db != null)
	        {
	        	Cursor c = db.rawQuery("SELECT * FROM Detalle", null);
	        	if (c.moveToFirst()) {
	        		zeroGastos = 1;
	        		String poi_idr = c.getString(1);
	        		String poi_nombre = c.getString(2);
	        		String poi_foto = c.getString(3);
	        		String poi_direccion = c.getString(4);
	        		String poi_metro = c.getString(5);
	        		String poi_metrobus = c.getString(6);
	        		String poi_servicios = c.getString(7);
	        		String poi_clasificacion = c.getString(8);
	        		String poi_www = c.getString(9);
	        		String poi_mail = c.getString(10);
	        		String poi_tel = c.getString(11);
	        		String poi_lat = c.getString(12);
	        		String poi_lng = c.getString(13);
	        		String poi_idioma = c.getString(14);
	        		String poi_ruta = c.getString(15);
	        		String poi_horario = c.getString(16);
	        		String poi_costo = c.getString(17);
	        		String poi_descripcion = c.getString(18);
	        		String poi_cuentaporcentaje = c.getString(19);
	        		String poi_entradalibre = c.getString(20);
	        		String poi_encabezado = c.getString(21);
	        		
	        		Log.i("BD_TabFragment", poi_idioma + poi_servicios + poi_foto + poi_descripcion + poi_costo + poi_metrobus + poi_metro );
	        	}else{
	        		zeroGastos = 0;
	        	}
	        	db.close();
	        }
			return null;
		}
		
		@Override
		protected void onPostExecute(String result) {
			super.onPostExecute(result);

			db.close();
		}
    	
    }
	
}